// components/CustomModal.tsx

import React, { useRef, forwardRef, useImperativeHandle } from 'react';
import { Dialog, Form, Input, Button, Select, Radio, Textarea, InputAdornment } from 'tdesign-react';
import styles from './index.module.less';
import { FormField } from 'types/Form.d';
import { useSingleMessage } from 'composables/useMessage';
import { throttle } from 'utils/index';

interface IModalProps {
  visible: boolean;
  width?: string;
  onClose?: () => void;
  title: string;
  onSubmit: (type: string, values: any, cb: () => void) => void;
  type: 'Add' | 'Edit';
  initialValues?: any;
  children?: React.ReactNode;
  fields?: any;
}
const { FormItem } = Form;
const SakuraModal = forwardRef(
  ({ visible, onClose, title, type, initialValues, width, fields, onSubmit }: IModalProps, ref) => {
    const { showMessage } = useSingleMessage();
    const renderFormItem = (field: FormField) => {
      switch (field.type) {
        case 'select':
          return <Select options={field.options} disabled={field.disabled} placeholder={`请选择`} clearable />;
        case 'input':
          if (field?.appendSuffix) {
            return (
              <InputAdornment append={field?.appendSuffix} style={{ width: '100%' }}>
                <Input
                  placeholder='请输入'
                  clearable
                  disabled={field.disabled}
                  onChange={(value) => handleInputChange(value, field)}
                />
              </InputAdornment>
            );
          }
          return (
            <Input
              placeholder='请输入'
              clearable
              disabled={field.disabled}
              onChange={(value) => handleInputChange(value, field)}
            />
          );

        case 'textarea':
          return <Textarea placeholder='请输入' clearable {...field.props} disabled={field.disabled} />;
        case 'radio':
          return (
            <Radio.Group defaultValue='gz'>
              {field.options.map((item) => (
                <Radio key={item.value} value={item.value} disabled={field.disabled}>
                  {item.label}
                </Radio>
              ))}
            </Radio.Group>
          );
        default:
          return <span>请设置组件类型type</span>;
      }
    };

    const handleInputChange = (value: string, field: FormField) => {
      if (field.numberType) {
        const reg = field.numberType === 'int' ? /^-?\d*$/ : /^-?\d*(\.\d*)?$/;
        if (value === '' || reg.test(value)) {
          form.setFieldsValue({ [field.name]: value });
        }
      } else {
        form.setFieldsValue({ [field.name]: value });
      }
    };

    const InitForm = () => {
      showMessage('success');
      form.clearValidate();
      form.reset();
      form.setFieldsValue({
        ...initialValues,
      });
    };
    // 根据类型设置标题和按钮文本
    const FormTitle = type === 'Add' ? `新增${title}` : `编辑${title}`;
    const buttonText = type === 'Edit' ? '新增' : '确定';
    const [form] = Form.useForm();
    const formRef = useRef(null);
    const handleSubmit = throttle(async () => {
      try {
        const res = await form.validate();
        if (Object.entries(res).length === 0) {
          const values = form.getFieldsValue(true);
          onSubmit(type, values, InitForm);
        }
      } catch (err) {}
    }, 1000); // 1秒节流

    useImperativeHandle(ref, () => ({
      setFieldError: (name: string, message: string) => {
        form.setFieldsValue({ name: 'email', message: '21' });
      },
      form,
    }));
    return (
      <Dialog
        visible={visible}
        onClose={onClose}
        header={FormTitle}
        onConfirm={(value) => {
        }}
        style={{ padding: '25px' }}
        width={width || '550px'}
        footer={
          <>
            <Button theme='default' onClick={onClose}>
              取消
            </Button>
            <Button form='custom-modal-form' onClick={handleSubmit}>
              {buttonText}
            </Button>
          </>
        }
      >
        <div className={styles['modal-content']}>
          <Form id='custom-modal-form' form={form} ref={formRef} initialData={initialValues}>
            {fields.map((field: FormField) => (
              <FormItem
                key={field.name}
                label={field.label}
                help={field?.help && <span style={{ color: '#7868e6' }}>{field?.help}</span>}
                name={field.name}
                rules={field.required ? [{ required: true, message: `${field.label}是必填项` }] : []}
              >
                {renderFormItem(field)}
              </FormItem>
            ))}
          </Form>
        </div>
      </Dialog>
    );
  },
);

export default SakuraModal;
